<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\home\controller;

use think\request;
use cmf\controller\HomeBaseController;
use think\queue\Queue;
use think\Db;
use think\Controller;
class TaskController extends Controller
{ 

	//---------------------------------普通用户 -> 顾问-----------------------------------------
	public function memberUpgrade()
	{
		WL(['msg' => '用户——>顾问'], 'upgrade');
		$memModel = new \app\home\model\MemberModel();
		$orderModel = new \app\home\model\OrdersModel();

		//找出已绑定邀请人的用户
		$str = 'member_id, nickname, grade, invite';
		$list = $memModel->getMemberWhereReturnList($str);
		$list = !empty($list) ? $list : [];

		//循环查找，是否满足条件
		WL(['msg' => '找出all普通用户', 'count' => count($list)], 'upgrade');
		foreach ($list as $key => $value) 
		{
			$money = $orderModel->getMemberOrderSuccess($value['member_id']);


			//购课金额，大于99元。就升级
			if($money > 0)
			{
				$memModel->updateMemberInfo($value['member_id'], ['grade' => 2]);

				//发送消息通知
				$notice_contro = new NoticeController();
				$send_data = [
	                'first' => ['value'=>'恭喜您升级为顾问', 'color'=>"#173177"],
	                'keyword1' => ['value'=> $value['nickname'], 'color'=>'#173177'],
	                'keyword2' => ['value'=> '顾问', 'color'=>'#173177'],
	                'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
	                'remark' => ['value'=>'恭喜升级成功，请点击此处了解等级权益', 'color'=>'#173177'],
	            ];
	            $return_url = WEB_URL."/grade";
	            $notice_contro->sendNoticeMessage('jj', $send_data, $return_url, '', $value['member_id']);

				WL(['msg' => '普通用户升级成功', 'member_id' => $value['member_id']], 'upgrade');
			}	
		}
		WL(['msg' => 'ok-用户->顾问'], 'upgrade');
	}



	//---------------------------------顾问 -> 星级顾问---------------------------------------------
	public function consultantUpgrade()
	{
		WL(['msg' => '顾问——>星级顾问'], 'upgrade');
		$memModel = new \app\home\model\MemberModel();
		$orderModel = new \app\home\model\OrdersModel();
		$oaModel = new \app\home\model\OrderAwardModel();

		//找出所有顾问
		$str = 'member_id, nickname, grade, invite';
		$list = $memModel->getMemberWhereUpgradeReturnList(2, $str);
		$list = !empty($list) ? $list : [];
		WL(['msg' => '找出all顾问', 'count' => count($list)], 'upgrade');
		foreach ($list as $key => $value) 
		{
			//直邀顾问数量
			$number_1 = $memModel->geetMemberInviteGradeTwoCount($value['invite']);
			if($number_1 < 1)
			{
				WL(['msg' => '没有直邀顾问'], 'upgrade');
				continue;
			}

			//团队顾问
			$number_2 = $this->teamConsultant($value['invite']);
			if($number_2 < 1)
			{
				WL(['msg' => '没有团队顾问'], 'upgrade');
				continue;
			}	

			//团队消费5元以上的人数
			/*$number_3 = $this->teamConsultantOrderSuccess($value['invite']);
			if($number_3 < 50)
			{
				WL(['msg' => '消费5元的人没有'], 'upgrade');
				continue;
			}*/	

			//个人推广收益30元
			$number_4 = $oaModel->memberOrderEarnings($value['member_id']);
			if($number_4 < 30)
			{
				WL(['msg' => '个人推广收益不够'], 'upgrade');
				continue;
			}

			//开始升级
			$memModel->updateMemberInfo($value['member_id'], ['grade' => 3]);

			//发送消息通知
			$notice_contro = new NoticeController();
			$send_data = [
                'first' => ['value'=>'恭喜您升级为星级顾问', 'color'=>"#173177"],
                'keyword1' => ['value'=> $value['nickname'], 'color'=>'#173177'],
                'keyword2' => ['value'=> '星级顾问', 'color'=>'#173177'],
                'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
                'remark' => ['value'=>'恭喜升级成功，请点击此处了解等级权益', 'color'=>'#173177'],
            ];
            $return_url = WEB_URL."/grade";
            $notice_contro->sendNoticeMessage('jj', $send_data, $return_url, '', $value['member_id']);

			WL(['msg' => '顾问升级成功', 'member_id' => $value['member_id']], 'upgrade');

		}

		WL(['msg' => 'ok-顾问——>星级顾问'], 'upgrade');
	}



	//---------------------------------星级顾问 -> 联合创始人---------------------------------------------
	public function starConsultantUpgrade()
	{
		WL(['msg' => '星级顾问->联合创始人'], 'upgrade');
		$memModel = new \app\home\model\MemberModel();
		$orderModel = new \app\home\model\OrdersModel();
		$oaModel = new \app\home\model\OrderAwardModel();

		//找出所有星级顾问
		$str = 'member_id, nickname, grade, invite';
		$list = $memModel->getMemberWhereUpgradeReturnList(3, $str);
		$list = !empty($list) ? $list : [];
		WL(['msg' => '找出all星级顾问', 'count' => count($list)], 'upgrade');
		foreach ($list as $key => $value) 
		{
			//直邀星级顾问数量
			$number_1 = $memModel->geetMemberInviteGradeTwoCount($value['invite'], 3);
			if($number_1 < 1)
			{
				WL(['msg' => '没有星级顾问'], 'upgrade');
				continue;
			}

			//团队顾问
			$number_2 = $this->teamConsultant($value['invite']);
			if($number_2 < 1)
			{
				WL(['msg' => '没有团队顾问'], 'upgrade');
				continue;
			}	

			//团队消费5元以上的人数
			/*$number_3 = $this->teamConsultantOrderSuccess($value['invite']);
			if($number_3 < 800)
			{
				WL(['msg' => '消费5元'], 'upgrade');
				continue;
			}*/	


			//个人推广收益500元
			$number_4 = $oaModel->memberOrderEarnings($value['member_id']);
			if($number_4 < 500)
			{
				WL(['msg' => '个人推广收益不够'], 'upgrade');
				continue;
			}

			//开始升级
			$memModel->updateMemberInfo($value['member_id'], ['grade' => 4]);

			//发送消息通知
			$notice_contro = new NoticeController();
			$send_data = [
                'first' => ['value'=>'恭喜您升级为联合创始人', 'color'=>"#173177"],
                'keyword1' => ['value'=> $value['nickname'], 'color'=>'#173177'],
                'keyword2' => ['value'=> '联合创始人', 'color'=>'#173177'],
                'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
                'remark' => ['value'=>'恭喜升级成功，请点击此处了解等级权益', 'color'=>'#173177'],
            ];
            $return_url = WEB_URL."/grade";
            $notice_contro->sendNoticeMessage('jj', $send_data, $return_url, '', $value['member_id']);

			WL(['msg' => '星级顾问升级成功', 'member_id' => $value['member_id']], 'upgrade');
		}
		WL(['msg' => 'ok-星级顾问 -> 联合创始人'], 'upgrade');
	}




	//-------------------------------------------已付款的课程，未发货的话。--------------------------------------
	//定时检测是否有新增的兑换码，有的话，就发货
	public function checkOrderStatusEqOneCourseCode()
	{
		//找出未发货的兑换码的订单,500条
		$orderModel = new \app\home\model\OrdersModel();
		$coursecodeModel = new \app\home\model\CourseCodeModel();
		$list = $orderModel->checkOrderStatusEqOneCourse();
		$list = !empty($list) ? $list : [];
		WL(['msg' => '未发货订单数量', 'count' => count($list)], 'zidong_fahuo');
		foreach ($list as $key => $value) {
			//查找课程兑换码
            $date = date('Y-m-d H:i:s');
            $code_where = [
                ['course_id', '=', $value['course_id']],
                ['start_time', '<=', $date], 
                ['end_time', '>=', $date],
                ['status', '=', 1],
            ];
            $code_info = $coursecodeModel->getCourseCodeInfo($code_where);
            //如果有兑换码，就开始绑定到当前订单上
            if(!empty($code_info))
            {
                Db::startTrans();
                //1.绑定到订单上
                $order_code_where = [
                    ['order_id', '=', $value['order_id']],
                    ['status', '=', 1],
                ];

                $update_code_order = [
                    'status' => 2,
                    'dispatch_time' => date('Y-m-d H:i:s'),
                    'course_code_id' => $code_info['id'],
                ];
                $res = $orderModel->updateOrders($order_code_where, $update_code_order);
                if(empty($res))
                {
                    WL([ 'msg' => '订单发货失败', 'order_id' => $value['order_id']],'zidong_fahuo');
                    //如果发货失败，等待定时任务，定时捞订单并发货。
                    Db::rollback();
                }else{

                    //2.发货成功，修改兑换码状态
                    $code_where = [
                        ['id', '=', $code_info['id']],
                        ['course_id', '=', $code_info['course_id']],
                        ['status', '=', 1],
                        
                    ];

                    $code_update = [
                        'status' => 2,
                        'order_id' => $value['order_id'],
                        'issue_time' => date('Y-m-d H:i:s'),
                    ];
                    $res = $coursecodeModel->updateCourseCodeWhereId($code_where, $code_update);
                    if(empty($res))
                    {
                        WL([ 'msg' => '更新订单绑定的兑换码状态失败', 'order_id' => $value['order_id']],'zidong_fahuo');
                        //如果发货失败，等待定时任务，定时捞订单并发货。
                        Db::rollback();
                    }else{
                         WL([ 'msg' => '订单发货成功，绑定兑换码OK', 'order_id' => $value['order_id']],'zidong_fahuo');
                    }
                    Db::commit();

                     //发货成功，通知消息
                    $notice_contro = new NoticeController();
                    $send_data = [
                        'first' => ['value'=>'您的订单已发货', 'color'=>"#173177"],
                        'keyword1' => ['value'=> $value['order_number'], 'color'=>'#173177'],
                        'keyword2' => ['value'=> $value['add_time'], 'color'=>'#173177'],
                        'keyword3' => ['value'=> '无', 'color'=>'#173177'],
                        'keyword4' => ['value'=> '无', 'color'=>'#173177'],
                        'keyword5' => ['value'=> $value['site'], 'color'=>'#173177'],
                        'remark' => ['value'=>'您的课程已开通，点击查看上课详情', 'color'=>'#173177']
                    ];
                    $return_url = WEB_URL."/order_details?order_id=".$value['order_id'];
                    $notice_contro->sendNoticeMessage('fh', $send_data, $return_url, '', $value['member_id']);
                }
            }
		}
		WL([ 'msg' => '未发货订单，自动发货完成'],'zidong_fahuo');
	}






	//--------------------------------------自动审核100元以下的提现----------------------------------------
	/*public function checkMemberTxVoluntarilyGrant()
	{
		WL(['msg' => '查找100元以下的提现中的用户'], 'member_tx');
		$wdModel = new \app\home\model\WithdrawalsModel();
		//找出所有100元以下未审核的提现
		$list = $wdModel->getMemberTxList();
		$list = !empty($list) ? $list : [];

		//一个个开始循环，操作
		WL(['msg' => '数据总数', 'count' => count($list)], 'member_tx');
		foreach ($list as $key => $value) {

			//修改状态,开始提现
			$res = $wdModel->updateMemberTxStatus();

			//开始提现
			Db::startTrans();

			//成功，增加财务日志
		}
	}*/



	/**
	*
	*团队顾问人数
	*$grade =2 顾问， =3星级顾问
	*
	**/
	protected function teamConsultant($invite, $grade = 2)
	{
		$memModel = new \app\home\model\MemberModel();
		$list = $memModel->geetMemberTeamNumber($invite);
		$list = !empty($list) ? $list : [];
		$team_number = 0;
		foreach ($list as $key => $value) {
			if($value['grade'] == $grade)
			{
				$team_number = $team_number + 1;
			}
		}

		foreach($list as $val)
		{
			$number = $this->teamConsultant($val['invite'], $grade);
			$team_number = $team_number + $number;
		}
		return $team_number;
	}



	/**
	*
	*团队-消费5元以上的用户
	*
	**/
	protected function teamConsultantOrderSuccess($invite)
	{
		$memModel = new \app\home\model\MemberModel();
		$orderModel = new \app\home\model\OrdersModel();
		$list = $memModel->getMemberTeamOrderNumber($invite);
		$list = !empty($list) ? $list : [];
		
		$count_number = 0;
		foreach($list as $val)
		{
			$number = $this->teamConsultantOrderSuccess($val['invite']);
			$count_number = $count_number + $number;
			$money = $orderModel->getMemberOrderSuccess($val['member_id']);
			if($money >= 5)
			{
				$count_number = $count_number + 1;
			}
		}
		return $count_number;
	}




	/**
	*
	*发货十天的订单，自动收货
	*
	**/
	public function orderAffirm()
	{
		WL([ 'msg' => '超十天的订单，自动收货完成'],'order_affirm');
		$orderModel = new \app\home\model\OrdersModel();
		//找出所有未收货的订单
		$list = $orderModel->orderAffirm();
		$list = !empty($list) ? $list : [];

		//循环，自动收货
		foreach($list as $key => $val)
		{
			$member_id = $val['member_id'];
			$order_id = $val['order_id'];

			//查看订单状态
			if($val['status'] != 2)
			{
				//$this->error('请确认订单状态');
				WL([ 'msg' => '订单状态已被改变'],'order_affirm');
				continue;
			}

			//开始修改状态和收货时间
			$where = [
				['member_id', '=', $member_id],
				['order_id', '=', $order_id],
				['status', '=', 2],
			];

			$update = [
				'status' => 4,
				'delivery_time' => date('Y-m-d H:i:s'),
			];
			$res = $orderModel->updateOrders($where, $update);
			if(empty($res))
			{
				//$this->error('确认收货失败，系统错误');
				WL([ 'msg' => '确认收货失败，系统错误'],'order_affirm');
				continue;
			}else{
				$this->issueAward($order_id);
				WL([ 'msg' => '确认收货成功', 'order_id' => $order_id],'order_affirm');
			}
		}
	}



	/**
	*
	*发放-佣金，管理奖励
	*
	**/
	protected function issueAward($order_id)
	{
		
		$orderModel = new \app\home\model\OrdersModel();
		$oaModel = new \app\home\model\OrderAwardModel();
		$memberModel = new \app\home\model\MemberModel();
		$financeModel = new \app\home\model\FinanceModel();
		//查找订单
		$where = [
			['order_id', '=', $order_id],
		];
		$info = $orderModel->memberOrderInfo($where, 'order_id, if_award');
		//只计算已计算的奖励
		if($info['if_award'] == 2)
		{
			//开始发放奖励
			$list = $oaModel->getOrderIdEarningsList($order_id);
			$list = !empty($list) ? $list : [];

			foreach ($list as $key => $value) {
				//直接修改状态，再发放金额
				Db::startTrans();
				$res = [];
				$res[] = $oaModel->updateOrderIdEarnings($value['id'], ['status' => 2]);

				//发放金额
				$memberinfo = $memberModel->getMemberIdWhereMemberId($value['member_id'], 'member_id, money');
				$money = $memberinfo['money'] + $value['money'];//余额+奖励金

				//发放
				$res[] = $memberModel->updateMemberInfo($value['member_id'], ['money' => $money]);

				//查询发放结果
				if(!in_array(false, $res))
				{
					Db::rollback();
				}else{
					$finance = [
						'member_id' => $value['member_id'],
						'type' => $value['award_type'],
						'money' => $value['money'],
						'remark' => ($value['award_type'] == 1) ? '订单收益' : '管理奖励',
						'status' => 2,
						'before_money' => $memberinfo['money'],
						'later_money' => $money,
					];
					$financeModel->addFinance($finance);
					Db::commit();

					//收货成功，通知消息
					if($value['money'] > 0)
					{	
						$source = ($value['award_type'] == 1) ? '订单收益' : '管理奖励';
						$notice_contro = new NoticeController();
						$send_data = [
			                'first' => ['value'=>'您有一笔新收益到账了', 'color'=>"#173177"],
			                'keyword1' => ['value'=> $value['money'], 'color'=>'#173177'],
			                'keyword2' => ['value'=> $source, 'color'=>'#173177'],
			                'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
			                'remark' => ['value'=>'点击查看收益详情', 'color'=>'#173177'],
			            ];
			            $return_url = WEB_URL."/award_list?type=".$value['award_type'];
			            $notice_contro->sendNoticeMessage('sy', $send_data, $return_url, '', $value['member_id']);
					}
				}
			}
			return true;
		}else{
			return false;
		}
	}



	public function test()
	{
		
       WL(['msg' => 'chmod-------------------------'], 'send_msg');
	}


}